package it.ap.sa.core.dao.util.serializer;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.io.WKTWriter;

/**
 * serializzatore geogson per una {@link Geometry} in WKT
 * @author 
 */
public class WKT3rdSerializer extends JsonSerializer<Geometry> {

	@Override
	public void serialize(Geometry value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {

		writeGeometry(jgen, value);
	}

	/**
	 * @param jgen
	 * @param value
	 * @throws JsonGenerationException
	 * @throws IOException
	 */
	public void writeGeometry(JsonGenerator jgen, Geometry value) throws JsonGenerationException, IOException {
		 WKTWriter wkt = new WKTWriter(3);
		 /** convert type Geometry to WKT **/
		 String val = wkt.write(value);
		 
		 /**
		  * Es json : "geometry":{"wkt":"POINT(16.27582497094736 41.16401442647753 0)"}
		  */
		 jgen.writeStartObject();
		 jgen.writeStringField("wkt", val);
		 jgen.writeEndObject();
	}
	 

	@SuppressWarnings("unused")
	private void writePoint(JsonGenerator jgen, Point p) throws JsonGenerationException, IOException {
		jgen.writeStartObject();
		jgen.writeStringField("type", "Point");
		jgen.writeFieldName("coordinates");
		writePointCoords(jgen, p);
		jgen.writeEndObject();
	}

	private void writePointCoords(JsonGenerator jgen, Point p) throws IOException, JsonGenerationException {
		jgen.writeStartArray();
		jgen.writeNumber(p.getX());
		jgen.writeNumber(p.getY());
		jgen.writeNumber(p.getCoordinate().z);
		jgen.writeEndArray();
	}
}
